package com.unitd.frame.springweb.interceptor;

import com.unitd.frame.springweb.annotation.ResponsePolicy;
import com.unitd.frame.springweb.constant.WebConstants;
import com.unitd.frame.comm.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @desc SpringMVC的默认拦截器,对web访问进行默认拦截处理
 * @filename GlobalDefaultInterceptor.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2017/3/29
 */
public class GlobalDefaultInterceptor implements HandlerInterceptor {

	private static Logger log = LoggerFactory.getLogger(GlobalDefaultInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		if (handler instanceof HandlerMethod) {
//			HandlerMethod method = (HandlerMethod) handler;
		}

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
						   ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		if (handler instanceof HandlerMethod) {
			HandlerMethod method = (HandlerMethod) handler;
			ResponsePolicy config = method.getMethod().getAnnotation(ResponsePolicy.class);
			if (config != null) {
				response.addHeader(WebConstants.HEADER_RESP_POLICY, StringUtils.join(config.value(), ','));
			}
		}
	}
}